package com.lingxu.api.ztb.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lingxu.api.ztb.mapper.ProjectScheduleMapper;
import com.lingxu.api.ztb.model.ProjectSchedule;
import com.lingxu.api.ztb.service.IProjectScheduleService;
import com.lingxu.api.ztb.model.vo.ProjectScheduleVO;



import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.metadata.IPage;


import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import javax.annotation.Resource;
import java.util.*;

/**
 * 项目进度计划表 服务实现类
 *
 * @author admin
 * @since 2025-08-08
 */
@Slf4j
@Service
public class ProjectScheduleServiceImpl extends ServiceImpl<ProjectScheduleMapper, ProjectSchedule>  implements IProjectScheduleService {

    @Resource
    private ProjectScheduleMapper projectScheduleMapper;

    @Transactional(readOnly = true)
    @Override
    public IPage<ProjectScheduleVO> queryPageList(ProjectScheduleVO query) {
        Page<ProjectScheduleVO> page = new Page<>(query.getPageNo(), query.getPageSize());
        IPage<ProjectScheduleVO> projectScheduleVOIPage = projectScheduleMapper.pageList(page, query);
        List<ProjectScheduleVO> projectList = projectScheduleVOIPage.getRecords();

        List<Map<String, Object>> progressList = projectScheduleMapper.getOverallProgress();
        Map<String, Double> progressMap = new HashMap<>();
        for (Map<String, Object> map : progressList) {
            String projectCode = (String) map.get("projectCode");
            Number progressNum = (Number) map.get("overallProgress");
            Double overallProgress = progressNum != null ? progressNum.doubleValue() : 0.0;
            progressMap.put(projectCode, overallProgress);
        }
        projectList.forEach(vo -> {
            Double progress = progressMap.getOrDefault(vo.getProjectCode(), 0.0);
            vo.setOverallProgress(String.format("%.2f", progress));
        });
        return projectScheduleVOIPage;
    }


    @Transactional(readOnly = true)
    @Override
    public List<ProjectScheduleVO> list(ProjectScheduleVO query) {
        return projectScheduleMapper.selectProjectScheduleList(query);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(Set<String> ids) {
        if (CollectionUtils.isNotEmpty(ids)) {
            projectScheduleMapper.deleteBatchIds(ids);
        }
    }

}
